package com.sunmouse.toolkit.fragment.other;


import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.app.NotificationCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;

import com.sunmouse.toollib.constants.Interaction;
import com.sunmouse.toollib.utils.FileUtils;
import com.sunmouse.toollib.utils.LogUtils;
import com.sunmouse.toollib.utils.ThreadPoolUtils;
import com.sunmouse.toollib.utils.ToastUtils;
import com.sunmouse.toollib.utils.load.LoadRequest;
import com.sunmouse.toollib.utils.load.LoadUtils;
import com.sunmouse.toollib.utils.region.RegionUtils;
import com.sunmouse.toollib.utils.system.PermissionUtil;
import com.sunmouse.toolkit.R;
import com.sunmouse.toolkit.fragment.BaseFragment;
import com.sunmouse.toolkit.util.PageUtil;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class OtherFragment extends BaseFragment {


    @BindView(R.id.parser_btn)
    Button parserBtn;
    @BindView(R.id.scroll_btn)
    Button scrollBtn;
    @BindView(R.id.select_Tv)
    TextView selectTv;
    @BindView(R.id.jump_btn)
    Button jumpBtn;
    @BindView(R.id.toast_btn)
    Button toastBtn;
    @BindView(R.id.log_btn)
    Button logBtn;
    @BindView(R.id.x_offset_sb)
    SeekBar xOffsetSb;
    @BindView(R.id.y_offset_sb)
    SeekBar yOffsetSb;
    @BindView(R.id.load_btn)
    Button loadBtn;
    @BindView(R.id.install_btn)
    Button installBtn;
    Unbinder unbinder;

    private static final int BASE_X_OFFSET = 0;
    private static final int BASE_Y_OFFSET = 0;
    private static final int SCALE = 20;
    @BindView(R.id.load_tool_btn)
    Button loadToolBtn;
    @BindView(R.id.provider_btn)
    Button providerBtn;

    private boolean debug = true;

    private int xOffset;
    private int yOffset;

    private LoadUtils mLoadUtils;
    public static final String localPath = FileUtils.getStoragePath() + "/resola/hello.apk";
    //    public static final String remoteUrl = "http://audio.vsaker.com/ysecret/secret-1.mp4";
    public static final String remoteUrl = "http://www.wandoujia.com/apps/com.jgw.supercode/download?pos=detail-ndownload-com.jgw.supercode";
    private NotificationManager notifyManager;
    private Timer mTimer;
    private TimerTask mTimerTask;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.activity_other, container, false);
        unbinder = ButterKnife.bind(this, v);
        return v;
    }

    @Override
    public void init() {
        parserBtn.setOnClickListener(this);
        scrollBtn.setOnClickListener(this);

        this.jumpBtn.setOnClickListener(this);
        this.toastBtn.setOnClickListener(this);
        this.logBtn.setOnClickListener(this);
        this.loadBtn.setOnClickListener(this);
        this.installBtn.setOnClickListener(this);
        this.selectTv.setOnClickListener(this);
        this.loadToolBtn.setOnClickListener(this);
        this.providerBtn.setOnClickListener(this);


        this.xOffsetSb.setOnSeekBarChangeListener(xOnSeekBarChangeListener);
        this.yOffsetSb.setOnSeekBarChangeListener(yOnSeekBarChangeListener);
        xOffset = BASE_X_OFFSET;
        yOffset = BASE_Y_OFFSET;

        notifyManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
        mTimer = new Timer();


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.parser_btn:
                parserXml();
                break;
            case R.id.install_btn:
                mIntent = new Intent();
                mIntent.setAction(Intent.ACTION_VIEW);
                mIntent.addCategory(Intent.CATEGORY_DEFAULT);
                mIntent.setDataAndType(Uri.fromFile(FileUtils.newFile(localPath)), "application/vnd.android.package-archive");
                getActivity().startActivity(mIntent);
                break;
            case R.id.load_btn:
                if (PermissionUtil.isPermitted(getActivity(), Interaction.Permissions.FILE_ACCESS)) {
                    loading();
                } else {
                    PermissionUtil.requestPermission(getActivity(), Interaction.Permissions.FILE_ACCESS, 5);
                }
                break;
            case R.id.scroll_btn:
                scrollBtn.scrollTo(-100, 0);
                scrollBtn.setSelected(true);
                break;
            case R.id.jump_btn:
                jump(PageUtil.Index.MENU);
                break;
            case R.id.toast_btn:
                ToastUtils.simpleToast(getActivity(), "Toast location");
                LogUtils.d("------toast_btn");
                break;
            case R.id.select_Tv:
                selectTv.setSelected(true);
                break;
            case R.id.load_tool_btn:
                jump(PageUtil.Index.LOAD);
                break;
            case R.id.provider_btn:
                jump(PageUtil.Index.PROVIDER);
                break;
        }
    }

    private void loading() {
        this.mLoadUtils = LoadUtils.init()
                .build(getActivity());
        this.mLoadUtils.addRequest(new LoadRequest.Builder(localPath, remoteUrl).build());
        this.mLoadUtils.enqueue(new LoadListener());

    }

    /**
     * release Timer
     */
    private void releaseTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer.purge();
            mTimer = null;
        }

    }

    private Notification generateNotification(int pro) {
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getActivity());
        mBuilder.setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(pro != 1000 ? "下载中....." : "下载完成")
                .setProgress(1000, pro, false)
                .setContentIntent(generatePending());
        return mBuilder.build();
    }

    private PendingIntent generatePending() {
        mIntent = new Intent();
//        mIntent.setClass(this,MainActivity.class);
        mIntent.setAction(Intent.ACTION_VIEW);
        mIntent.addCategory(Intent.CATEGORY_DEFAULT);
        mIntent.setDataAndType(Uri.fromFile(FileUtils.newFile(localPath)), "application/vnd.android.package-archive");
        LogUtils.d("-----------pending....");

        return PendingIntent.getActivity(getActivity(), 5, mIntent, PendingIntent.FLAG_ONE_SHOT);
    }


    /**
     * parser xml
     */
    private void parserXml() {
        ThreadPoolUtils.execute(new TimerTask() {
            @Override
            public void run() {
                RegionUtils.loadingProvince(getActivity());
            }
        });
    }

    /**
     * x offset change listener
     */
    private SeekBar.OnSeekBarChangeListener xOnSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                xOffset = BASE_X_OFFSET + SCALE * (progress - 50);
                LogUtils.d("-------xOffset=" + xOffset);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    };
    /**
     * y offset change listener
     */
    private SeekBar.OnSeekBarChangeListener yOnSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                yOffset = BASE_Y_OFFSET + SCALE * (progress - 50);
                LogUtils.d("-------yOffset=" + yOffset);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    };


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            loading();
        }
    }

    private class LoadingTimerTask extends TimerTask {
        @Override
        public void run() {
            int pro = (int) ((float) mLoadUtils.getProgress() / mLoadUtils.getLength() * 1000);
            notifyManager.notify(1, generateNotification(pro));
            LogUtils.d("---------pro=" + pro);
        }
    }

    /**
     * load listener
     */
    class LoadListener implements LoadUtils.OnLoadingListener{
        @Override
        public void onStart(int position) {
            ToastUtils.simpleToast(getActivity(), "start-----");
            mTimer.schedule(new LoadingTimerTask(), 0, 1000);
        }

        @Override
        public void onLoading(int length, int progress, int position) {

        }

        @Override
        public void onStop(int progress, int position) {

        }

        @Override
        public void onComplete(int position) {

        }

        @Override
        public void onError(Exception e, int position) {

        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();

        releaseTimer();
    }
}
